import mysql = require('mysql');

const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: 'root',
  database: 'mybatis',
});

async function getConnection() {
  return new Promise((resolve, reject) => {
    pool.getConnection((err, connection) => {
      if (err) {
        reject(err);
      }
      resolve(connection);
    });
  });
}

async function getQueryResult(connection, query) {
  return new Promise((resolve, reject) => {
    // const query = mysql.format(sqlString, sqlValueArray);
    console.log('执行的sql: ' + query);
    connection.query(query, (err, rows) => {
      // connection 不放回连接池，等用完完了让他自己放回 (让执行事务操作时是同一个connection)
      // connection.release();
      if (err) {
        reject(err);
      }
      resolve(rows);
    });
  });
}

async function getSqlResult(sqlString: string) {
  let result = void 0;
  if (sqlString) {
    const connection = await getConnection();
    result = await getQueryResult(connection, sqlString);
  }
  return result;
}

module.exports = {
  getConnection,
  getQueryResult,
  getSqlResult,
};
